<template>
  <div class="example">
    <div class="box" ref="box"></div>
    <div class="btn">
      <button @click="handleClick">{{ isShow ? '隐藏' : '显示' }}</button>
    </div>
  </div>
</template>

<script>
/**
 * 可以把它进一步封装成指令的形式
 */
export default {
  data() {
    return {
      isShow: true
    }
  },
  watch: {
    isShow(val) {
      const prefix = 'fade';
      if (val) {
        this.$refs.box.classList.add(`${prefix}-enter`);
        this.$refs.box.style.display = '';
        this.$refs.box.classList.add(`${prefix}-enter-active`);
        this.$refs.box.classList.add(`${prefix}-enter-to`);
        setTimeout(() => {
          this.$refs.box.classList.remove(`${prefix}-enter`);
          this.$refs.box.addEventListener('transitionend', (e) => {
            this.$refs.box.classList.remove(`${prefix}-enter-active`);
            this.$refs.box.classList.remove(`${prefix}-enter-to`);
          });
        });
      } else {
        this.$refs.box.classList.add(`${prefix}-leave-active`);
        this.$refs.box.classList.add(`${prefix}-leave-to`);
        this.$refs.box.addEventListener('transitionend', (e) => {
          this.$refs.box.classList.remove(`${prefix}-leave-active`);
          this.$refs.box.classList.remove(`${prefix}-leave-to`);
          this.$refs.box.style.display = 'none';
        });
      }
    }
  },
  methods: {
    handleClick() {
      this.isShow = !this.isShow
    }
  }
}
</script>

<style lang="less" scoped>
.fade-enter-active, .fade-leave-active {
  transition: opacity 3s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
</style>
